package cn.tj212.xiaoyin.web;

import cn.tj212.xiaoyin.common.web.SessionContext;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

//验证码生成器
@Controller
@RequestMapping("/tools/identify")
public class IdentifyCodeController {

    @RequestMapping("code")
    public void init(HttpServletRequest request, HttpServletResponse response){
        String random= RandomStringUtils.randomAlphanumeric(4);
        SessionContext.setAttribute(request,SessionContext.IDENTIFY_CODE_KEY,random);
        response.setContentType("image/jpeg");
        response.addHeader("pragma","No-cache");
        response.addHeader("Cache-Control","no-cache");
        response.addDateHeader("Expires",0);
        int width=110,height=33;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics=image.getGraphics();
        //以下填充背景色
        graphics.setColor(new Color(225,225,225));
        Font DeFont=new Font("SansSerif",Font.PLAIN,26);
        graphics.setFont(DeFont);
        graphics.fillRect(0,0,width,height);
        //设置字体色
        graphics.setColor(Color.BLACK);
        graphics.drawString(random,20,25);
        graphics.dispose();
        try {
            ServletOutputStream outputStream=response.getOutputStream();
            ImageIO.write(image,"JPG",outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
